var _vdefaultpage = "Default.aspx";
var _vhandlerpath = 'handlers/';
var _vhandler_auth = _vhandlerpath + 'Auth.ashx';
var _vhandler_form = _vhandlerpath + 'Forms.ashx';
var _vloginpageid = '707D34CC-8B4B-4649-B2F2-47017D4E4723';
var _vlastobj;

$(function () {
    $("[data-load]").each(function () {
        $(this).load($(this).data("load"), function () {
        });
    });
});



/* EVENT LISTENERS */
$(function () {
    _fw_ajax_init();
    _fw_setTabNavigator();
    $('.page-tabs-outer .page-tabs .tabs li.active a:first').click();
    _fw_formReload('_AHMIDEA_HOME');
    $(document).click(function (e) {
        if($(e.target).closest('.main-sidebar').length<=0) $(".main-sidebar").slideUp();
    });
    // handle enter key on login popup
    $('#loginBlock input[type="text"], #loginBlock input[type="password"]').keydown(function (e) {
        if (e.keyCode == 13) {
            $('#loginBlock .login-button').click();
        }
    });
})

$(window).resize(function () {
    _fw_setTabNavigator();
    _fw_initWidth();
})

//METRO_AUTO_REINIT = true;


/* FRAMEWORK FUNCTIONS */
function _fw_initWidth() {
    var ww = $(window).width();
    if (ww <= 480) {
        $('.tblDetailView').hide();
    } else if (ww <= 640) {
        $('.tblDetailView, .tblDetailView.dtlpriority2').hide();
    } else if (ww <= 800) {
        $('.tblDetailView, .tblDetailView.dtlpriority2, .tblDetailView.dtlpriority3').hide();
    } else {
        $('.tblDetailView, .tblDetailView.dtlpriority2, .tblDetailView.dtlpriority3, .tblDetailView.dtlpriority4').hide();
    }
}

function _fw_loaderShow() { $("#ajax-loading, .ajax-loader-block").show(); }
function _fw_loaderHide() { $("#ajax-loading, .ajax-loader-block").hide(); }

function _fw_ajax_init() {
    $(document).ajaxStart(function () {
        _fw_loaderShow()
    }).ajaxComplete(function () {
        _fw_loaderHide()
    }).ajaxError(function (a, b, c) {
        if ((b.status == '401') && ($('#loginBlock').length > 0)) {
            _fw_openLoginForm();
        } else {
            $.Dialog({
                shadow: true,
                overlay: false,
                icon: '<span class="icon-cancel fg-crimson"></span>',
                title: 'Request Error',
                width: 500,
                padding: 10,
                content: '<h1><span class="icon-cancel fg-crimson"></span> Error ' + b.status + '</h1><div class="errMessage">' + b.statusText + '</div><div class="errDetail"><div class="errDetailDump"><!-- [##### REQUEST DUMP ON : ' + (new Date()).toString() + ' #####]--> Type : ' + c.type + '; Url : ' + c.url + '; Data : ' + c.data + ' <!-- [##### RESPONSE DUMP #####]--> ' + b.responseText.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;') + '</div></div><div class="dialogButtons"><button class="primary" type="button"><span class="icon-mail"></span> Report Error</button> <button class="primary danger" type="button" onclick="$.Dialog.close()"><span class="icon-cancel-2"></span> Close</button></div>'
            });
        }
    });
}

function _fw_setTabNavigator() {
    if ($('.page-tabs').length > 0) {
        var bw = $('.page-tabs').width();
        var sw = $('.page-tabs')[0].scrollWidth;
        if (sw > bw+2) {
            $('.page-tabs-outer .tabs-controls').show();
            $('.page-tabs-outer .page-tabs').addClass('scrollable');
        } else {
            $('.page-tabs-outer .tabs-controls').hide();
            $('.page-tabs-outer .page-tabs').removeClass('scrollable');
        }
    }
}

function _fw_setTabNext() {
    var obj = $('.page-tabs-outer .page-tabs .tabs li.active');
    if (obj.next().length > 0) {
        var nbj = obj.removeClass('active').next().addClass('active').find('a:first').click();
        $('.page-tabs-outer .page-tabs').animate({ scrollLeft: nbj.position().left - $('.page-tabs-outer .page-tabs .tabs').position().left });
    } else {
        $('.page-tabs-outer .page-tabs').animate({ scrollLeft: obj.position().left - $('.page-tabs-outer .page-tabs .tabs').position().left });
    }
}

function _fw_setTabPrev() {
    var obj = $('.page-tabs-outer .page-tabs .tabs li.active');
    if (obj.prev().length > 0) {
        var nbj = obj.removeClass('active').prev().addClass('active').find('a:first').click();
        $('.page-tabs-outer .page-tabs').animate({ scrollLeft: nbj.position().left - $('.page-tabs-outer .page-tabs .tabs').position().left });
    } else {
        $('.page-tabs-outer .page-tabs').animate({ scrollLeft: obj.position().left - $('.page-tabs-outer .page-tabs .tabs').position().left });
    }
}

function _fw_setTabClose(obj) {
    var pr = obj.closest('li');
    $(obj.prev().attr('href')).remove();
    if (pr.prev().length > 0) {
        $('a:first', pr.prev()).click();
    } else {
    $('.page-tabs .tabs li:first a:first').click();
    }
    pr.remove();
    _fw_setTabNavigator();
    _fw_setLocationHash();
}

function _fw_setTabOpen(obj) {
    var tgt = obj.attr('href');
    $('.page-tabs .tabs li.active').removeClass('active');
    obj.parent().addClass('active');
    $('.tab-frames .tab-frame').hide();
    $(tgt).show();
    window.setTimeout(_fw_setLocationHash,10);
}

function _fw_setTabOpenHome() {
    $('.tabs .tab-label[href="#_AHMIDEA_HOME"]').click();
}

function _fw_reloadHome() {
    $('#_AHMIDEA_HOME #refreshHomeButton').click();
}

function _fw_setLocationHash() {
    var tabs = $('.page-tabs .tab-label');
    var th = '';
    if (_vloadhash_state && (document.location.hash != '')) {
        var ah = document.location.hash.split(',');
        if (tabs.length >= ah.length - 1) { _vloadhash_state = false; }
        return;
    }
    tabs.each(function () {
        if ($(this).parent().hasClass('active')) {
            th += $(this).attr('href').replace('#', '') + ':1,';
        } else th += $(this).attr('href').replace('#', '') + ',';
    });
    document.location.hash = th;
}

var _vloadhash_state = true;
function _fw_formLoadFromHash() {
    if (document.location.hash != '') {
        var ah = document.location.hash.split(',');
        var acttab = '';
        for (var x = 0; x < ah.length; x++) {
            var xs = ah[x].split(':');
            if (xs.length > 1) acttab = xs[0].replace('#','');
            $('#mainMenuContainer a[data-formid="' + xs[0].replace('#', '') + '"]').click();
        }
    }
    $('.page-tabs a.tab-label[href="#' + acttab + '"]').click();
}

var _tmpobj;
function _fw_formLoad(obj) {
    _vlastobj = obj;
    var formid = obj.data('formid');
    var appid = obj.data('appid');
    var formicon = obj.data('form-icon') == '' ? '' : '<span class="' + obj.data('form-icon') + '"></span> ';
    var fid = obj.data('fid');
    var formurl = obj.attr('href');
    var formlabel = obj.text();
    var formapp = obj.closest('li[data-group]');
    formapp = formapp.length > 0 ? ' title="'+formapp.data('group')+' : '+formlabel+'"' : '';
    if ((formurl != '') && (formurl != '#')) {
        var tabobj = $('.page-tabs .tabs li a.tab-label[href="#' + formid + '"]');
        if (tabobj.length > 0) {
            _tmpobj = tabobj; window.setTimeout(function () { _tmpobj.click() }, 10); //tabobj.click();
            var ctxid = $('#' + formid + '.tab-frame');
            if ((ctxid.length > 0) && (ctxid.html() == '')) { _fw_formReload(formid); }
        } else {
            $('.page-tabs .tabs li.active').removeClass('active');
            $('.tab-frames .tab-frame').hide();
            var tab = $('<li class="active" ' + formapp + '><a class="tab-label" href="#' + formid + '" onclick="_fw_setTabOpen($(this)); return false;">' +formicon+ formlabel + '</a><a href="#' + formid + '" class="icon-cancel-2 tab-close-link" onclick="_fw_setTabClose($(this)); return false;"></a></li>').appendTo($('.page-tabs .tabs'));
            var tabContent = $('<div class="tab-frame" id="' + formid + '" data-url="' + formurl + '" data-appid="'+appid+'" data-formid="'+fid+'" ></div>').appendTo($('.tab-frames')).show();
            var _url = _fw_setQuerytringParam(formurl, 'cb', (new Date()).getTime());
            $.get(_url, {}, function (data) {
                if (data.indexOf(_vloginpageid) == -1) {
                    // load content only if session is not expired
                    _fw_loaderShow();
                    tabContent.html(data);
                    _fw_loaderHide();
                    $.Metro.initAll();
                } else { _fw_openLoginForm(); }
            });
        }
        _fw_setTabNavigator();
        _fw_setTabNext();
    }
}

function _fw_formReload(frameid) {
    var obj = $('#' + frameid);
    if (obj.length > 0) {
        var url = obj.data('url');
        $.get(url, {}, function (data) {
            if (data.indexOf(_vloginpageid) == -1) {
                _fw_loaderShow();
                obj.html(data);
                _fw_loaderHide();
                $.Metro.initAll();
            } else { _fw_openLoginForm(); }
        });
    }
}

function _fw_formReloadCurrent(obj) {
    _vlastobj = obj;
    _fw_formReload($(obj).closest('.tab-frame').attr('id'));
}

function _fw_generateCb() {
    var d = new Date();
    return d.getFullYear() + '_' + d.getMonth() + '_' + d.getDate();
}


/* User Auth */
function _fw_openLoginForm() {
    $('#loginBlock').show();
    $('#loginBlock .login-outer').slideDown();
    $('#loginBlock .login-outer :input[name="pass"]').focus();
}

function _fw_userlogin(formid) {
    $('.message-box').html('').hide();
    var url = _fw_setQuerytringParam(_vhandler_auth, 'cb', (new Date()).getTime());
    $.post(url, $(':input', formid).serialize(), function (ret) {
        if (ret.status == '1') {
            if (ret.redirect_url != '') {
                document.location = ret.redirect_url;
            } else {
                document.location = _vdefaultpage;
            }
        } else {
            $('.message-box').html(ret.message).slideDown();
        }
    });
}

function _fw_userrelogin(formid) {
    $('.message-box').html('').hide();
    var url = _fw_setQuerytringParam(_vhandler_auth, 'cb', (new Date()).getTime());
    $.post(url, $(':input', formid).serialize(), function (ret) {
        if (ret.status == '1') {
            if (_vlastobj && ($(_vlastobj).length > 0)) $(_vlastobj).trigger('click');
            $('#loginBlock .login-outer').slideUp(function () {
                $('#loginBlock').hide();
                $('#loginBlock input[type="password"]').val('');
            });
        } else {
            $('.message-box').html(ret.message).slideDown();
        }
    });
}

function _fw_userlogout() {
    $('.message-box').html('').hide();
    var url = _fw_setQuerytringParam(_vhandler_auth, 'cb', (new Date()).getTime());
    $.post(url, { 'action': 'logout' }, function (ret) {
        if (ret.status == '1') {
            document.location = ret.redirect_url;
        } else {
            $('.message-box').html(ret.message).slideDown();
        }
    });
}

/* Sub Pages */
function _fw_navigateBreadcrumb(obj,path) {
    var obj = $(obj); var objframe = obj.closest('.tab-frame'); var subpages = $('.sub-page', objframe).hide();
    var objtarget = subpages.filter('[data-path="' + path + '"]');
    if (objtarget.length > 0) { _fw_navigateSubPage(obj, objtarget.data('section')); } else {
        _fw_navigateSubPage(obj, $('.sub-page.sub-page-default', objframe).data('section'));
        _fw_setTabOpenHome();
    }
    _fw_setMessage(objframe, -1, "");
}

function _fw_navigateToObject(obj) {
    var top = obj.position().top-100;
    if (top>0) $('body').animate({ scrollTop: top }, 300);
}

function _fw_navigateSubPage(obj, section) {
    var obj = $(obj); var objframe = obj.closest('.tab-frame'); var subpages = $('.sub-page', objframe).hide();
    var objtarget = subpages.filter('[data-section="' + section + '"]').show();
    var tpath = objtarget.data('path').split('>');
    var tp1 = []; var tl = '';
    for (var i = 0; i < tpath.length; i++) {
        if (i < tpath.length - 1) tp1[tp1.length] = tpath[i];
        else tl = tpath[i];
    }
    var hdr = $('.form-header h1', objframe);  var bc = $('.form-header nav.breadcrumbs ul', objframe);
    hdr.html('<a href="#" onclick="_fw_navigateBreadcrumb(this,\'' + tp1.join('>') + '\'); return false;" ><i class="icon-arrow-left-3 fg-darker smaller"></i></a>  ' + tl + ' ');
    bc.empty();
    var ttp = '';
    for (var x = 0; x < tp1.length; x++) {
        ttp = ttp == '' ? tp1[x] : ttp + '>' + tp1[x];
        bc.append('<li><a href="#" onclick="_fw_navigateBreadcrumb(this,\'' + ttp + '\'); return false;">' + tp1[x] + '</a></li>');
    }
    bc.append('<li class="active"><a>' + tl + '</a></li>');
    _fw_setMessage(objframe, -1, "");
}

function _fw_loadSubPage(objSect, getParam, onLoaded) {
    var url = objSect.html('Loading content...').data('url');
    $.each(getParam, function (key, val) {
        url = _fw_setQuerytringParam(url, key, val);
    });
    objSect.data('url', url);
    url = _fw_setQuerytringParam(url, 'cb', (new Date()).getTime())
    $.get(url, {}, function (data) {
        if (data.indexOf(_vloginpageid) == -1) {
            _fw_loaderShow();
            objSect.html(data);
            _fw_loaderHide();
            $.Metro.initAll();
            if (typeof onLoaded == 'function') onLoaded();
        } else { _fw_openLoginForm(); }
    });
}


/* Data Submission */
function _fw_formSaveDraft(obj) {
    _vlastobj = obj;
    var obj = $(obj);
    var frame = obj.closest('.tab-frame');
    var frameid = frame.attr('id');
    var frame_appid = frame.data('appid');
    var frame_formid = frame.data('formid');
    var fcontent = $('.sub-pages', frame);
    if (fcontent.length <= 0) fcontent = frame;
    $('input', fcontent).each(function () {
        if (($(this).attr('type') == "radio") || ($(this).attr('type') == "checkbox")) $(this).attr('checked', $(this).prop('checked'));
        else $(this).attr('value', $(this).val());
    });
    $('textarea', fcontent).each(function () { $(this).html($(this).val()); });
    $('select', fcontent).each(function () { $(this).find(':selected').attr('selected', 'selected'); });
    var url = _fw_setQuerytringParam(_vhandler_form, 'cb', (new Date()).getTime());
    $.post(url, { 'action': 'ADDSTATE', 'appid': frame_appid, 'formid': frame_formid, 'state': escape(fcontent.html()) }, function (data) {
        if (data.status && (data.status == '1')) {
            $('span', obj).removeClass('icon-bookmark-2').addClass('icon-bookmark');
            obj.unbind('click').attr('title', 'Open Draft').attr('onclick', '').click(function () { _fw_formOpenDraft(this); });
            _fw_reloadHome();
        } else if ((typeof data != 'object') && (data.indexOf(_vloginpageid) > -1)) {
            _fw_openLoginForm();
        }
    });
}

function _fw_formOpenDraft(obj) {
    _vlastobj = obj;
    var obj = $(obj);
    var frame = obj.closest('.tab-frame');
    var frameid = frame.attr('id');
    var frame_appid = frame.data('appid');
    var frame_formid = frame.data('formid');
    var fcontent = $('.sub-pages', frame);
    if (fcontent.length <= 0) fcontent = frame;
    var url = _fw_setQuerytringParam(_vhandler_form, 'cb', (new Date()).getTime());
    $.post(url, { 'action': 'GETSTATE', 'appid': frame_appid, 'formid': frame_formid }, function (data) {
        if ((data != '') && (data.indexOf(_vloginpageid) == -1)) {
            fcontent.html(data);
            $('span', obj).removeClass('icon-bookmark').addClass('icon-bookmark-2');
            obj.unbind('click').attr('title', 'Save Draft').attr('onclick', '').click(function () { _fw_formSaveDraft(this); });
            _fw_reloadHome();
            $.Metro.initAll();
        } else { _fw_openLoginForm(); }
    });
}

function _fw_formSetFavorite(obj) {
    _vlastobj = obj;
    var obj = $(obj);
    var frame = obj.closest('.tab-frame');
    var frameid = frame.attr('id');
    var frame_appid = frame.data('appid');
    var frame_formid = frame.data('formid');
    var url = _fw_setQuerytringParam(_vhandler_form, 'cb', (new Date()).getTime());
    $.post(url, { 'action': 'ADDFAV', 'appid': frame_appid, 'formid': frame_formid }, function (data) {
        if ((typeof data != 'object') && (data.indexOf(_vloginpageid) > -1)) {
            _fw_openLoginForm();
        } else {
            if (data.status && (data.status == '1')) {
                $('span', obj).removeClass('icon-star').addClass('icon-star-3');
                obj.attr('title', 'Remove Favorite').unbind('click').attr('onclick', '').click(function () { _fw_formUnsetFavorite(this); });
                _fw_reloadHome();
            }
        }
    });
}

function _fw_formUnsetFavorite(obj) {
    _vlastobj = obj;
    var obj = $(obj);
    var frame = obj.closest('.tab-frame');
    var frameid = frame.attr('id');
    var frame_appid = frame.data('appid');
    var frame_formid = frame.data('formid');
    var url = _fw_setQuerytringParam(_vhandler_form, 'cb', (new Date()).getTime());
    $.post(url, { 'action': 'DELFAV', 'appid': frame_appid, 'formid': frame_formid }, function (data) {
        if ((typeof data != 'object') && (data.indexOf(_vloginpageid) > -1)) {
            _fw_openLoginForm();
        } else {
            if (data.status && (data.status == '1')) {
                $('span', obj).removeClass('icon-star-3').addClass('icon-star');
                obj.attr('title', 'Add Favorite').unbind('click').attr('onclick', '').click(function () { _fw_formSetFavorite(this); });
                _fw_reloadHome();
            }
        }
    });
}

function _fw_formResetFields(objframe) {
    objframe.html(objframe.html());
    $('.input-control.error-state', objframe).removeClass('error-state');
    var topFrame = objframe.closest('.tab-frame');
    _fw_setMessage(topFrame, -1, "");
    $.Metro.initAll();
}

function _fw_getActionUrl(formurl) {return formurl.replace('pages', 'handlers').replace('.aspx', '.ashx'); }

function _fw_postData(obj, sel, url, successFunc) {
    _vlastobj = obj;
    var sel = !sel ? '.form-maincontent' : sel;
    var pdata = $(sel + ' :input', $(obj).closest('.tab-frame')).serialize();
    var objsel = $(sel, $(obj).closest('.tab-frame'));
    var url = !url ? _fw_getActionUrl($(obj).closest('.tab-frame').data('url')) : url;
    _fw_setMessage($(obj).closest('.tab-frame'), -1, "");
    $(sel + ' .input-control', $(obj).closest('.tab-frame')).removeClass('error-state');
    url = _fw_setQuerytringParam(url, 'cb', (new Date()).getTime());
    $.post(url, pdata, function (data) {
        if ((typeof data != 'object') && (data.indexOf(_vloginpageid) > -1)) {
            _fw_openLoginForm();
        } else {
            _fw_processFormResponse($(obj).closest('.tab-frame'), sel, data);
            if (data.status && (data.status=='1') && (typeof successFunc == 'function')) {
                successFunc(obj);
            }
        }
    });
}

function _fw_processFormResponse(frameobj, sel, data) {
    if (data.status) {
        var emsg = ""
        if (data.error_fields) {
            var fld;
            for (var x = 0; x < data.error_fields.length; x++) {
                emsg += '<li>' + data.error_fields[x].m + '</li>';
                fld = $(sel + ' :input[name="' + data.error_fields[x].f + '"]', frameobj);
                if (fld.length > 0) fld.parent().addClass('error-state');
            }
            if (emsg != '') emsg = '<ul class="errorList">' + emsg + '</ul>';
        } else {
            emsg = $('<textarea />').html(data.message).val();
        }
        _fw_setMessage(frameobj, data.status, emsg);
    }
    
}



function _fw_setMessage(frameobj, type, msg) {
    var obj = $('.message-box', frameobj).empty().removeClass('success').removeClass('error').html(msg);
    if (type == 1) obj.addClass('success');
    else if (type == 0) obj.addClass('error');
    if (msg.replace('/\s/g', '') == '') obj.hide(); else {
        obj.slideDown();
        $(obj).closest('.metro').animate({ scrollTop: 0 });
    }
}

function _fw_openUploadForm(obj, url, maxFile, type, onSuccessFunc) {
    _vlastobj = obj;
    if (!url || (url == '')) url = $(obj).closest('.tab-frame').data('url');
    var dmsg = '';
    if (!onSuccessFunc) onSuccessFunc = function () { };
    switch (type) {
        case 'pictures':
            dmsg = '<h1>Drop image file here</h1> <h4>(or click)</h4>';
            break;
        case 'file-excel':
            dmsg = '<h1>Drop excel(.xslx) file here</h1> <h4>(or click)</h4>';
            break;
        default:
            dmsg = '<h1>Drop file here</h1> <h4>(or click)</h4>';
            break;
    }
    if ($('.dropzone-box.dropzone-outer').length > 0) $('.dropzone-box.dropzone-outer').remove();
    var uf = $('<div class="dropzone-box dropzone-outer"><div class="dropzone-button"><a href="#" onclick="$(\'.dropzone-box.dropzone-outer\').remove(); return false;" class="icon-cancel"></a></div><div class="dz-dropbox"><div class="dz-dropmessage"><span class="icon-' + type + ' block"></span><div class="msgtxt">' + dmsg + '</div></div><form class="dropzone dz-clickable" id="xlsDropZone" enctype="multipart/form-data" method="post" action=""><input type="hidden" name="action" value="UPLOAD"></form></div></div>').appendTo('body');
    Dropzone.options.xlsDropZone = {
        maxFiles: maxFile,
        success: function (file, response) {
            if (response.status) {
                _fw_setMessage($(obj).closest('.tab-frame'), response.status, response.message);
                if (response.status == '1') {
                    if (response.data) onSuccessFunc(response.data); else onSuccessFunc();
                }
            } else {
                if ((typeof response != 'object') && (response.indexOf(_vloginpageid) > -1)) {
                    _fw_openLoginForm();
                }
            }
        },
        complete: function (file) {
            $('.dropzone-box.dropzone-outer').remove();
        },
        init: function () {
            this.on("addedfile", function (file) { $('.dropzone-box.dropzone-outer .dz-dropmessage').hide(); });
        }
    };
    $('form', uf).dropzone({ url: _fw_getActionUrl(url) });
}

/* Table Functions */
function _fw_setQuerytringParam(location, key, value) {
    if (key == 'undefined') return location;
    var nqs = {};
    if (location && (location.indexOf('?') > -1)) {
        var afloc = location.split('?');
        var qs = afloc[1].split('&');
        var kv;
        for (var i = 0; i < qs.length; i++) {
            kv = qs[i].split('=');
            nqs[kv[0]] = typeof kv[1]!='undefined'? kv[1] : '';
        }
        location = afloc[0];
    }
    nqs[key] = value;
    var snqs = '';
    for (var k in nqs) {
        if (nqs.hasOwnProperty(k) && (k != 'undefined') && (nqs[k] != '')) {
            snqs += snqs == '' ? k + '=' + nqs[k] : '&' + k + '=' + nqs[k];
        }
    }
    if (snqs != '') snqs = '?' + snqs;
    return location + snqs;
}
function _fw_table_filter(obj, target, onSuccessFunc) {
    _vlastobj = obj;
    var fbox = $(obj).closest('.filter-panel');
    var ftab = $(obj).closest('.sub-page[data-url]').length>0? $(obj).closest('.sub-page[data-url]') : $(obj).closest('.tab-frame');
    var floc = ftab.data('url');
    var snqs = floc;
    $(':input', fbox).each(function () {
        snqs = _fw_setQuerytringParam(snqs, $(this).attr('name'), $(this).val());
    });
    snqs = _fw_setQuerytringParam(snqs, 'cb', (new Date()).getTime());
    ftab.data('url', snqs).attr('data-url', snqs);
    target.html('Loading data...');
    $.post(_fw_getActionUrl(snqs), { 'action': 'FILTER' }, function (data) {
        if (data.indexOf(_vloginpageid) > -1) {
            _fw_openLoginForm();
        } else {
            target.html(data);
            $.Metro.initAll();
            if (typeof onSuccessFunc == 'function') {
                onSuccessFunc();
            }
        }
    });
}
function _fw_table_checkall(obj) {
    var obj = $(obj);
    var tbl = obj.closest('table');
    $('tbody .tblData.checks input[type="checkbox"]', tbl).prop('checked', obj.prop('checked'));
    _fw_toggleDeleteButton(tbl.attr('id'), obj.prop('checked'));
}
function _fw_table_check(obj) {
    var obj = $(obj);
    var tbl = obj.closest('table');
    var allchecked = true;
    var anychecked = false;
    $('tbody .tblData.checks input[type="checkbox"]', tbl).each(function () {
        if (!$(this).prop('checked')) { allchecked = false; }
        else { anychecked = true; }
    });
    $('thead .tblHeader.checks input[type="checkbox"]', tbl).prop('checked', allchecked);
    _fw_toggleDeleteButton(tbl.attr('id'),anychecked);
}
function _fw_toggleDeleteButton(tableid,enable) {
    var obj = $('.tableButtons[data-table-id="' + tableid + '"] .btnDeleteData');
    if (enable) obj.show(); else obj.hide();
}
function _fw_table_sort(obj, fieldname, dir) {
    _vlastobj = obj;
    var tbl = $(obj).closest('.listContainer');
    var ftab = $(obj).closest('.sub-page[data-url]').length > 0 ? $(obj).closest('.sub-page[data-url]') : $(obj).closest('.tab-frame');
    var addr = ftab.data('url');
    addr = _fw_setQuerytringParam(addr, 'sortby', fieldname);
    addr = _fw_setQuerytringParam(addr, 'sortdir', dir);
    ftab.data('url', addr).attr('data-url', addr);
    addr = _fw_setQuerytringParam(addr, 'cb', (new Date()).getTime());
    $.post(_fw_getActionUrl(addr), { 'action': 'SORT', 'sortby': fieldname, 'sortdir': dir }, function (data) {
        if (data.indexOf(_vloginpageid) > -1) {
            _fw_openLoginForm();
        } else {
            tbl.html(data);
            $.Metro.initAll();
        }
    });
}
function _fw_table_showdetail(obj) {
    var obj = $(obj);
    var tgt = $('.tblDetailView', obj.closest('td')).slideToggle();
}
function _fw_tableGotoPage(obj, pagenum) {
    _vlastobj = obj;
    var tbl = $(obj).closest('.listContainer');
    var ftab = $(obj).closest('.sub-page[data-url]').length > 0 ? $(obj).closest('.sub-page[data-url]') : $(obj).closest('.tab-frame');
    var addr = ftab.data('url');
    ftab.data('url', addr).attr('data-url', addr);
    addr = _fw_setQuerytringParam(addr, 'cb', (new Date()).getTime());
    $.post(_fw_getActionUrl(addr), { 'action' : 'GOTO_PAGE', 'page':pagenum }, function (data) {
        if (data.indexOf(_vloginpageid) > -1) {
            _fw_openLoginForm();
        } else {
            tbl.html(data);
            $.Metro.initAll();
        }
    });
}

function _fw_tableAddRow(tableId, arrayData, withRowNumber) {
    var tbl = $('table#' + tableId);
    var maxrow = $('tbody tr',tbl).length;
    if (tbl.length > 0) {
        var hasDtlView = ($('thead .detailView', tbl).length > 0);
        var hdrMaxPr = 1;
        $('thead td, thead th', tbl).each(function () {
            if (!$(this).hasClass('rowNumber') && !$(this).hasClass('actionColumn')) {
                if ($(this).hasClass('priority4') && (hdrMaxPr < 4)) hdrMaxPr = 4;
                else if ($(this).hasClass('priority3') && (hdrMaxPr < 3)) hdrMaxPr = 3;
                else if ($(this).hasClass('priority2') && (hdrMaxPr < 2)) hdrMaxPr = 2;
            }
        });
        var dtlView = '';
        var rowStr = '<tr>';
        if (withRowNumber && ($('thead .rowNumber', tbl).length>0)) {
            var classNum = $('thead .rowNumber', tbl).attr('class').replace('tblHeader', 'tblData');
            rowStr += '<td class="' + classNum + '">' + (maxrow + 1) + '</td>';
        }
        $.each(arrayData, function (key, value) {
            var th = $('thead [data-field-id="' + key + '"]', tbl);
            var dtl = '';
            var linkDtl = '';
            if (th.length > 0) {
                var cpr = 'dtlpriority1';
                if (th.hasClass('priority2')) cpr = 'dtlpriority2';
                if (th.hasClass('priority3')) cpr = 'dtlpriority3';
                if (th.hasClass('priority4')) cpr = 'dtlpriority4';

                if (!th.hasClass('hidden') && !th.hasClass('mainfield') && !th.hasClass('actionColumn')) dtlView += '<div class="' + cpr + (th.hasClass('detailView')? ' view' : '') + '"><div class="detailview-label">' + th.text() + '</div><div class="detailview-value">' + value + '</div></div>';
                if (th.hasClass('mainfield')) {
                    dtl = '<div class="tblDetailView dtlpriority' + hdrMaxPr + '"><!--[dview]--></div>';
                    linkDtl = '<a href="#" class="linkdetail button icon-arrow-down-5 bg-transparent priority' + hdrMaxPr + '" onclick="_fw_table_showdetail(this); return false;"></a>';
                }
                var hfield = (!th.hasClass('rowNumber') && !th.hasClass('actionColumn')) ? '<input type="hidden" name="' + key + '" value="' + value + '">' : '';
                rowStr += '<td data-field-id="' + key + '" class="' + th.attr('class').replace('tblHeader', 'tblData') + (hasDtlView ? ' hasDetailView' : '') + '">' + linkDtl + '<span class="field-value">' + value + '</span>' + dtl + hfield + '</td>';
            }
        });
        rowStr = rowStr.replace('<!--[dview]-->',dtlView);
        rowStr += '</tr>';
        var newRow = $(rowStr);
        $('tbody', tbl).append(newRow);
        $.Metro.initAll();
        return newRow;
    }
}

function _fw_tableRenumbering(tableId) { 
    var tbl = $('table#' + tableId);
    if (tbl.length > 0) {
        $('tbody tr:not(:hidden)').each(function (i, e) {
            $('td.rowNumber', this).html(i+1);
        });
    }
}

function _fw_tableMoveRowUp(obj) {
    var tgt = $(obj).closest('tr').prev();
    if (tgt.is('tr')) { tgt.before($(obj).closest('tr')); _fw_tableRenumbering($(obj).closest('table').attr('id')); }
}

function _fw_tableMoveRowDown(obj) {
    var tgt = $(obj).closest('tr').next();
    if (tgt.is('tr')) { tgt.after($(obj).closest('tr')); _fw_tableRenumbering($(obj).closest('table').attr('id')); }
}

function _fw_tableDeleteRow(obj) {
    var tgt = $(obj).closest('tr').remove(); _fw_tableRenumbering($(obj).closest('table').attr('id'));
}

function _fw_tableActionLinks(sortButton, delButton) {
    var btns = '';
    if (sortButton) {
        btns += '<a class="tblActionUp" onclick="_fw_tableMoveRowUp(this); return false;" title="Move Up"><i class="icon-arrow-up fg-darkCyan"></i></a>&nbsp;<a class="tblActionBottom" onclick="_fw_tableMoveRowDown(this); return false;" title="Move Down"><i class="icon-arrow-down fg-darkCyan"></i></a>';
    }
    if (delButton) {
        btns += ' &nbsp;&nbsp;<a class="tblActionDel" onclick="_fw_tableDeleteRow(this); return false;" title="Delete Row"><i class="icon-cancel-2 fg-red"></i></a>&nbsp; ';
    }
    return btns;
}


/* jQuery Expressions Extension */
$.expr[":"].icontains = $.expr.createPseudo(function (arg) {
    return function (elem) {
        return $(elem).text().toLowerCase().indexOf(arg.toLowerCase()) >= 0;
    };
});

/* Validation */
var _vvalObjs = [];
function _fw_validation_clear(obj) {
    _vvalObjs = [];
    var ofrm = $(obj).closest('.tab-frame');
    _fw_setMessage(ofrm, -1, '');
    $('.input-control.error-state', ofrm).removeClass('error-state');
}
function _fw_validation_add(obj, fieldName, validation) {
    var ofrm = $(obj).closest('.sub-page').length > 0 ? $(obj).closest('.sub-page') : $(obj).closest('.tab-frame');
    var fieldLabel = $(':input[name="' + fieldName + '"]', ofrm).parent().prev().is('label') ? $(':input[name="' + fieldName + '"]', ofrm).parent().prev().text() : '';
    _vvalObjs[_vvalObjs.length] = { obj: $(':input[name="' + fieldName + '"]', ofrm), name:fieldLabel, val: validation , msg:'' };
}
function _fw_validation_validate(obj) {
    var ofrm = $(obj).closest('.tab-frame');
    var msgbox = $('.message-box', ofrm);
    var msg = '<ul class="errorList">';
    for (var i = 0; i < _vvalObjs.length; i++) {
        switch (_vvalObjs[i].val.toLowerCase()) {
            case 'required':
                if ((_vvalObjs[i].msg=='') && (_vvalObjs[i].obj.val().replace(/\s+/,'')=='')) _vvalObjs[i].msg = 'Field '+_vvalObjs[i].name+' is required.';
                break;
            case 'number':
                if ((_vvalObjs[i].msg=='') && isNaN(_vvalObjs[i].obj.val())) _vvalObjs[i].msg = 'Field ' + _vvalObjs[i].name + ' must be numeric.';
                break;
        }
    }
    var dmsg = '';
    for (var i = 0; i < _vvalObjs.length; i++) {
        if (_vvalObjs[i].msg != '') {
            dmsg += '<li>' + _vvalObjs[i].msg + '</li>';
            _vvalObjs[i].obj.closest('.input-control').addClass('error-state');
        }
    }
    if (dmsg != '') {
        msg += dmsg + '</ul>';
        _fw_setMessage(ofrm, 0, msg);
        return false;
    }
    return true;
}